<template>
  <div id="selectDepartment">
    <el-dialog
      title="选择部门"
      :visible.sync="dialogData.isShow"
      class="about-set"
      width="420px"
      :before-close="labelHandleClose"
    >
      <el-input v-model="filterText" placeholder="输入关键字进行过滤" />
      <el-tree
        :data="data"
        :props="defaultProps"
        :expand-on-click-node="false"
        ref="tree"
        :default-expand-all="isShowList"
        :highlight-current="true"
        :filter-node-method="filterNode"
        check-on-click-node
        check-strictly
        node-key="id"
        @node-click="handleNodeClick"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelLabel">取 消</el-button>
        <el-button type="success" :loading="loading" @click="confirmLabel"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getTree } from '@/api/system/department' // 接口
export default {
  name: 'SelectDepartment',
  msg: '选择部门弹窗',
  props: ['dialogData'],
  data() {
    return {
      filterText: '',
      isShowList: true, // 是否全部展开
      data: [],
      defaultProps: {
        children: 'childs',
        label: 'name'
      },
      selectNode: {},
      loading: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getDataList()
  },
  methods: {
    /* 获取部门信息树状结构 */
    async getDataList() {
      let _this = this
      await getTree((response) => {
        _this.data = response
        _this.$nextTick(function() {
          _this.$refs.tree.setCheckedKeys(this.dialogData.selectId)
        })
      })
    },
    /* 筛选关键字 */
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleNodeClick(data, node, cur) {
      this.selectNode = { ...data }
      // 实现单选
      if (node) {
        this.$refs.tree.setCheckedNodes([])
        this.$refs.tree.setCheckedNodes([data])
      }
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    confirmLabel() {
      this.loading = true
      this.$emit('getDepartName', this.selectNode)
      this.cancelLabel()
    },
    cancelLabel() {
      // 关闭前清空
      this.selectNode = {}
      this.loading = false
      this.filterText = ''
      this.dialogData.isShow = false
      // selectId此处不能清空，否则再次点开弹窗，没有数据回填
      // this.dialogData.selectId = []
    }
  }
}
</script>

<style lang="less">
#selectDepartment {
  .el-tree-node.is-checked {
    & > .el-tree-node__content {
      background-color: #1dc8a4 !important;
      color: #fff;
    }
  }
  .el-dialog__body {
    min-height: 310px !important;
    max-height: 400px;
    overflow: auto;
  }
  .el-input {
    margin-bottom: 15px;

    .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
  }
}
</style>
